package com.freedom.mediaplayer.service;

import java.util.ArrayList;
import java.util.List;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.IBinder;
import android.view.animation.AnimationUtils;

import com.freedom.mediaplayer.R;
import com.freedom.mediaplayer.app.AppConstant;
import com.freedom.mediaplayer.entity.LrcContent;
import com.freedom.mediaplayer.entity.Music;
import com.freedom.mediaplayer.fragment.LrcPage;
import com.freedom.mediaplayer.until.DataUtil;
import com.freedom.mediaplayer.until.LrcProcess;
import com.freedom.mediaplayer.until.MusicUntil;

public class PlayService extends Service {
	private MediaPlayer mediaPlayer;
	private boolean isPause;
	private String path;
	private int status = 3; // 播放状态，默认为顺序播放
	private int currentTime = 0; // 当前播放进度
	private int duration; // 播放长度
	// private int curPosition;
//	private List<Music> list;
	private MyReceiver myReceiver;
	private LrcProcess mLrcProcess; // 歌词处理
	private List<LrcContent> lrcList = new ArrayList<LrcContent>(); // 存放歌词列表对象
	private int index = 0; // 歌词检索值

	public static final String UPDATE_ACTION = "com.freedom.action.UPDATE_ACTION"; // 更新动作
	public static final String CTL_ACTION = "com.freedom.action.CTL_ACTION"; // 控制动作
	public static final String MUSIC_CURRENT = "com.freedom.action.MUSIC_CURRENT"; // 当前音乐播放时间更新动作
	public static final String MUSIC_DURATION = "com.freedom.action.MUSIC_DURATION";// 音乐长度更新动作
	public static final String SHOW_LRC = "com.freedom.action.SHOW_LRC"; // 通知显示歌词
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				if (mediaPlayer != null) {
					currentTime = mediaPlayer.getCurrentPosition();
					Intent intent = new Intent();
					intent.setAction(MUSIC_CURRENT);
					intent.putExtra("duration", duration);
					intent.putExtra("currentTime", currentTime);
					DataUtil.isPlaying = mediaPlayer.isPlaying();
					sendBroadcast(intent);
					handler.sendEmptyMessageDelayed(1, 990);
				}
			}
		};
	};
	private int msg;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mediaPlayer = new MediaPlayer();
		//list = MusicUntil.getMp3Infos(PlayService.this);
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				if (status == 1) { // 单曲循环
					mediaPlayer.start();
				} else if (status == 2) { // 全部循环
					DataUtil.curPosition++;
					if (DataUtil.curPosition > DataUtil.list.size() - 1) { // 变为第一首的位置继续播放
						DataUtil.curPosition = 0;
					}
					Intent sendIntent = new Intent(UPDATE_ACTION);
					// sendIntent.putExtra("curPosition", curPosition);
					sendBroadcast(sendIntent);
					path = DataUtil.list.get(DataUtil.curPosition).getUrl();
					play(0);
				} else if (status == 3) { // 顺序播放
					DataUtil.curPosition++; // 下一首位置
					if (DataUtil.curPosition <= DataUtil.list.size() - 1) {
						Intent sendIntent = new Intent(UPDATE_ACTION);
						// sendIntent.putExtra("curPosition", curPosition);
						// 发送广播，将被Activity组件中的BroadcastReceiver接收到
						sendBroadcast(sendIntent);
						path = DataUtil.list.get(DataUtil.curPosition).getUrl();
						play(0);

					} else {
						mediaPlayer.seekTo(0);
						DataUtil.curPosition = 0;
						Intent sendIntent = new Intent(UPDATE_ACTION);
						// sendIntent.putExtra("curPosition", curPosition);
						// 发送广播，将被Activity组件中的BroadcastReceiver接收到
						sendBroadcast(sendIntent);
					}
				} else if (status == 4) { // 随机播放
					DataUtil.curPosition = getRandomIndex(DataUtil.list.size() - 1);
					Intent sendIntent = new Intent(UPDATE_ACTION);
					// sendIntent.putExtra("curPosition", curPosition);
					sendBroadcast(sendIntent);
					path = DataUtil.list.get(DataUtil.curPosition).getUrl();
					play(0);
				}
				// SharedPrefencetUntil.setSharedPrefence(getApplicationContext(),
				// curPosition);
			}
		});
		myReceiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(CTL_ACTION);
		filter.addAction(SHOW_LRC);
		registerReceiver(myReceiver, filter);

	}

	private int getRandomIndex(int i) {
		int index = (int) (Math.random() * i);
		return index;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		path = intent.getStringExtra("url");
		// curPosition = DataUtil.curPosition;
		// curPosition = intent.getIntExtra("curPosition", 0);
		msg = intent.getIntExtra("MSG", 0);
		if (msg == AppConstant.PlayerMsg.PLAY_MSG) { // 直接播放音乐
			play(0);
		} else if (msg == AppConstant.PlayerMsg.PAUSE_MSG) { // 暂停
			pause();
		} else if (msg == AppConstant.PlayerMsg.STOP_MSG) { // 停止
			stop();
		} else if (msg == AppConstant.PlayerMsg.CONTINUE_MSG) { // 继续播放
			resume();
		} else if (msg == AppConstant.PlayerMsg.PRIVIOUS_MSG) { // 上一首
			previous();
		} else if (msg == AppConstant.PlayerMsg.NEXT_MSG) { // 下一首
			next();
		} else if (msg == AppConstant.PlayerMsg.PROGRESS_CHANGE) { // 进度更新
			currentTime = intent.getIntExtra("progress", -1);
			play(currentTime);
		} else if (msg == AppConstant.PlayerMsg.PLAYING_MSG) {
			handler.sendEmptyMessage(1);
		}
		return super.onStartCommand(intent, flags, startId);
	}

	private void resume() {
		// TODO Auto-generated method stub
		if (isPause) {
			mediaPlayer.start();
			isPause = false;
		}
	}

	private void next() {
		// TODO Auto-generated method stub
		Intent sendIntent = new Intent(UPDATE_ACTION);
		// sendIntent.putExtra("curPosition", curPosition);
		sendBroadcast(sendIntent);
		play(0);
	}

	private void previous() {
		// TODO Auto-generated method stub
		Intent sendIntent = new Intent(UPDATE_ACTION);
		// sendIntent.putExtra("curPosition", curPosition);
		sendBroadcast(sendIntent);
		play(0);
	}

	private void pause() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
			isPause = true;
		}
	}

	private void play(int currentTime) {
		try {
			// System.out.println("I am OO");
			// if (new File(path.replace(".mp3", ".lrc")).exists()) {
			// System.out.println("I am Here");
			// initLrc();
			// }
			mediaPlayer.reset();// 把各项参数恢复到初始状态
			mediaPlayer.setDataSource(path);
			mediaPlayer.prepare(); // 进行缓冲
			mediaPlayer
					.setOnPreparedListener(new PreparedListener(currentTime));// 注册一个监听器
			handler.sendEmptyMessage(1);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 停止音乐
	 */
	private void stop() {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			try {
				mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDestroy() {
		if (mediaPlayer != null) {
			System.out.println("Ser,De");
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
			unregisterReceiver(myReceiver);
		}
	}

	/**
	 * 初始化歌词配置
	 */
	public void initLrc() {
		mLrcProcess = new LrcProcess();
		// 读取歌词文件
		mLrcProcess.readLRC(DataUtil.list.get(DataUtil.curPosition).getUrl());
		// 传回处理后的歌词文件
		lrcList = mLrcProcess.getLrcList();
		LrcPage.lrcView.setmLrcList(lrcList);
		// 切换带动画显示歌词
		LrcPage.lrcView.setAnimation(AnimationUtils.loadAnimation(
				PlayService.this, R.anim.alpha_z));
		handler.post(mRunnable);
	}

	Runnable mRunnable = new Runnable() {

		@Override
		public void run() {
			LrcPage.lrcView.setIndex(lrcIndex());
			LrcPage.lrcView.invalidate();
			handler.postDelayed(mRunnable, 100);
		}
	};

	/**
	 * 根据时间获取歌词显示的索引值
	 * 
	 * @return
	 */
	public int lrcIndex() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			currentTime = mediaPlayer.getCurrentPosition();
			duration = mediaPlayer.getDuration();
		}
		if (currentTime < duration) {
			for (int i = 0; i < lrcList.size(); i++) {
				if (i < lrcList.size() - 1) {
					if (currentTime < lrcList.get(i).getLrcTime() && i == 0) {
						index = i;
					}
					if (currentTime > lrcList.get(i).getLrcTime()
							&& currentTime < lrcList.get(i + 1).getLrcTime()) {
						index = i;
					}
				}
				if (i == lrcList.size() - 1
						&& currentTime > lrcList.get(i).getLrcTime()) {
					index = i;
				}
			}
		}
		return index;
	}

	private final class PreparedListener implements OnPreparedListener {
		private int currentTime;

		public PreparedListener(int currentTime) {
			this.currentTime = currentTime;
		}

		@Override
		public void onPrepared(MediaPlayer mp) {
			mediaPlayer.start(); // 开始播放;
			if (currentTime > 0) { // 如果音乐不是从头播放
				mediaPlayer.seekTo(currentTime);
			}
			Intent intent = new Intent();
			intent.setAction(MUSIC_DURATION);
			duration = mediaPlayer.getDuration();
			intent.putExtra("duration", duration); // 通过Intent来传递歌曲的总长度
			sendBroadcast(intent);
		}
	}

	public class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mediaPlayer != null) {
				int control = intent.getIntExtra("control", -1);
				switch (control) {
				case 1:
					status = 1; // 将播放状态置为1表示：单曲循环
					break;
				case 2:
					status = 2; // 将播放状态置为2表示：全部循环
					break;
				case 3:
					status = 3; // 将播放状态置为3表示：顺序播放
					break;
				case 4:
					status = 4; // 将播放状态置为4表示：随机播放
					break;
				}
			}

			String action = intent.getAction();
			if (action.equals(SHOW_LRC)) {
				// System.out.println("I Hava Receive");
				// curPosition = intent.getIntExtra("curPosition", -1);
				initLrc();
			}
		}
	}

}
